package org.example.demo7.web.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

/**
 * @author zyp
 * @version 1.0
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
        //给登录相关的资源放行
        String[] urls={"GenerateCaptchaServlet","VerifyServlet","index.jsp","styles.css","img/","SelectUserServlet"};
        for (String url:urls){
            if(httpRequest.getRequestURI().contains(url)){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        //判断是否登录
        //判断session中是否有userName
        Object userName = httpRequest.getSession().getAttribute("userName");
        //判断userName是否为null
        if(userName!=null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            //没有登录，存储提示信息，重定向到登录页面
            httpRequest.setAttribute("result","您尚未登录！");
            httpRequest.getRequestDispatcher("index.jsp").forward(servletRequest,servletResponse);
        }
        }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void destroy() {

    }
}
